package com.xbjtech.vipsystem.controller;

import com.github.pagehelper.PageInfo;
import com.xbjtech.vipsystem.dto.Menu;
import com.xbjtech.vipsystem.po.User;
import com.xbjtech.vipsystem.service.UserService;
import com.xbjtech.vipsystem.utils.ArgumentResolver;
import com.xbjtech.vipsystem.vo.Result;
import com.xbjtech.vipsystem.vo.UserOptVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author leejun.happy@gmail.com
 * @created 2019-07-29
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api
public class UserController {

    @Autowired
    UserService userService;

    @ApiOperation(value = "获取列表分页数据")
    @GetMapping("/data")
    public Map<String, Object> data(
            @RequestParam(value = "page", required = false, defaultValue = "1")
                    int page,
            @RequestParam(value = "limit", required = false, defaultValue = "10")
                    int limit) {
        PageInfo<User> rolePageInfo = userService.selectByExamplePage(page, limit, null);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", rolePageInfo.getTotal());
        map.put("data", rolePageInfo.getList());
        return map;
    }

    @PostMapping("/save")
    public Result<String> save(@Validated @RequestBody User user) {
        try {
            if (user.getId() == null) {
// 新增操作
                user.setDeleted(0);
                user.setHeadId(0);
                user.setCreateTime(new Date());
                userService.insertWithoutPrimaryKey(user);
            } else {
// 修改操作
                User basic = userService.selectByPrimaryKey(user.getId());
                ArgumentResolver<User> resolver = new ArgumentResolver<>();
                User result = resolver.resolver(basic, user, User.class);
                userService.updateByPrimaryKey(result);
            }
            return Result.ok("保存成功");
        } catch (Exception e) {
            log.error("{}", e.getMessage());
        }
        return Result.fail("保存失败");
    }

    /**
     * restful
     * 查  get/role/1
     * 改  put/role
     * 增  post   /role
     * 删  delete /role/1
     *
     * @return
     */
    @ApiOperation(value = "通过id删除用户信息")
    @GetMapping("/remove/{id}")
    public Result<String> delete(@PathVariable Integer id) {
        try {
            userService.deleteByPrimaryKey(id);
            return Result.ok("删除成功");
        } catch (Exception e) {
            log.error("delete()方法发生异常：{}", e.getMessage());
        }
        return Result.fail("删除失败");
    }


    /**
     * POST
     * 先确定好发什么类型的POST请求
     * application/json
     * {
     * userId:1,
     * roleIds:[1,2,3,4]
     * }
     * application/x-www-form-urlencoded
     * Post => GET :/res/opt?roleId=1&resIds=1&resIds=2...
     *
     * @return
     */
    @ApiOperation(value = "给特定某一个用户分配角色")
    @PostMapping("/opt")
    public Result<String> opt(@Validated @RequestBody UserOptVO userOptVO) {
        try {
            userService.insertRoleRelation(userOptVO);
            return Result.ok("分配成功");
        } catch (Exception e) {
            log.error("{}", e.getMessage());
        }
        return Result.fail("分配失败");
    }

    @PostMapping(value = "/getmenus", produces = "application/json;charset=UTF-8")
    public List<Menu> getmenu() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        // 不同用户登录，应该显示的菜单列表是不一样的
        // 跟据不同的用户，获取不同的list
        // 查库
        return userService.selectMenus(user.getUsername());
    }

}
